// pages/SaoLei/SaoLei.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    str: '不好意思，您输了。下次走运！',
    showtime:0,//显示的时间
    isTimeStart:0,//开始计时标志
    playerLeiNum:10,//玩家雷数
    leiNum:10,//系统雷数
    over:0,//游戏状态
    win:0,
    clickmode: 0,//点击模式
    bestTime: 9999,//最佳时间
    gameNum: 0,//游戏次数
    gWinNum: 0,//获胜次数
    shenglv: 0,//胜率
    scrollFlag: true,//是否可以滑动
    vh100: 100,//100vh的具体值
    scaleNum: 1,//缩放比
    tobox0: '',
    testNum: 0,
    LeiMapX: new Array(9),//行格子数
    LeiMapY: new Array(9),//列格子数
    LeiMapArray: new Array(),//雷数组
    ClassArray:new Array(),//类数组
    NumArray: new Array(),//数字数组
    //0屏幕宽度，1小盒子宽度，2游戏盒子宽度,3游戏盒子高度
    WidthArray:['360px','40px','360px','360px'],
    //显示gameover盒子,显示选项盒子,显示雷,显示动画
    ShowDiv:[0,0,0,1],
  
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    that.getWidth();//获取屏幕宽度
    that.setTime();//计时函数
    console.log('1');
    that.startGame();//开始函数

    
    
    
  },
  startGame:function(){//游戏开始函数
    var that = this;
    that.setLocal();//设置localStorage
    that.cshArray();//初始化数组
    console.log(that.data.ClassArray.join("\n"));//打印雷数组
    setTimeout(function(){//播放动画
      that.data.ShowDiv[3] = 0;
      that.setData({
        ShowDiv:that.data.ShowDiv,
      })
    },1300)
    

  },
  cshArray:function(){
    var that = this;
    var YN = that.data.LeiMapY.length;
    var XN = that.data.LeiMapX.length;
    //初始化数组
    that.data.LeiMapArray = new Array();
    that.data.ClassArray = new Array();
    that.data.NumArray = new Array();
    for (var r = 0; r < YN; r++) {
      that.data.LeiMapArray[r] = new Array();
      that.data.ClassArray[r] = new Array();
      that.data.NumArray[r] = new Array();
      for (var c = 0; c < XN; c++) {
        that.data.LeiMapArray[r][c] = 0;
        that.data.ClassArray[r][c] = 0;
        that.data.NumArray[r][c] = 0;
      }
    }
    that.setData({//更新数据
      LeiMapArray: that.data.LeiMapArray,
      ClassArray: that.data.ClassArray,
      NumArray: that.data.NumArray,
      ShowDiv: [0, 0, 0, 1],
      isTimeStart: 0,
      showtime: 0,
      over: 0,
      win:0,
      clickmode: 0,
      playerLeiNum:that.data.leiNum,
    })

  },
  setLocal:function(){
    var t = parseInt(wx.getStorageSync('BestTime1'));
    if (!t) {
      wx.setStorageSync('BestTime1', 99999);//设置最佳时间1
      wx.setStorageSync('BestTime2', 99999);//设置最佳时间2
      wx.setStorageSync('BestTime3', 99999);//设置最佳时间3
      wx.setStorageSync('gameNum1', 0);//游戏次数1
      wx.setStorageSync('gameNum2', 0);//游戏次数2
      wx.setStorageSync('gameNum3', 0);//游戏次数3
      wx.setStorageSync('gWinNum1', 0);//获胜次数1
      wx.setStorageSync('gWinNum2', 0);//获胜次数2
      wx.setStorageSync('gWinNum3', 0);//获胜次数3
    }

  },
  setGameData:function(){
    var that = this;
    var local, bestTimeStr, gameNumStr, gWinNumStr;
    switch(that.data.leiNum)
    {
      case 10:
        bestTimeStr = 'BestTime1'
        gameNumStr = 'gameNum1'
        gWinNumStr = 'gWinNum1'
        break;
      case 40:
        bestTimeStr = 'BestTime2'
        gameNumStr = 'gameNum2'
        gWinNumStr = 'gWinNum2'
        break;
      case 99:
        bestTimeStr = 'BestTime3'
        gameNumStr = 'gameNum3'
        gWinNumStr = 'gWinNum3'
        break;
    }
    //设置获胜次数
    if (that.data.win){
      local = parseInt(wx.getStorageSync(gWinNumStr));
      local++;//赢次数+1
      wx.setStorageSync(gWinNumStr, local);
      if (that.data.showtime < parseInt(wx.getStorageSync(bestTimeStr)))
        wx.setStorageSync(bestTimeStr, that.data.showtime);//记录最佳时间
    }
    //设置最佳时间
    if (parseInt(wx.getStorageSync(bestTimeStr)) == 99999) {
      that.data.bestTime = '无'
    }
    else {
      that.data.bestTime = wx.getStorageSync(bestTimeStr);
    }
    //设置已玩次数
    local = parseInt(wx.getStorageSync(gameNumStr));
    local++;//游戏次数+1
    wx.setStorageSync(gameNumStr, local);
    //设置胜率
    local = parseInt(wx.getStorageSync(gameNumStr));
    var localWin = parseInt(wx.getStorageSync(gWinNumStr));
    local = parseInt((localWin/local)*10000)/100

    
    that.setData({
      bestTime: that.data.bestTime,
      gameNum: wx.getStorageSync(gameNumStr),
      gWinNum: wx.getStorageSync(gWinNumStr),
      shenglv: local,
    })

  },
  setclickmode:function(e){
    var c= e.currentTarget.dataset.clickmode;
    this.setData({
      clickmode:c,
    })
    
  },
  leftClick: function ( x, y) {
    var that = this;
    var XN = that.data.LeiMapY.length;
    var YN = that.data.LeiMapX.length;
    // console.log(that.checkLeiMap());
    console.log('leftclick x='+x+',y='+y);
    if (that.data.ClassArray[x][y] == 0){
      console.log('x='+x+',y='+y+',islei='+that.data.LeiMapArray[x][y]);
      //如果没有布置雷设置雷数组并开始计时
      if (!that.checkLeiMap()) {
        that.setLeiArray(x, y);
        that.setData({
          isTimeStart:1,
          over: 1,
        })
      }
      
        //如果有雷
        if (that.data.LeiMapArray[x][y] == 1) {
          console.log('有雷!');
          that.setGameData();//设置游戏数据
          that.data.ShowDiv[0]=1;//显示gameover盒子
          that.data.ShowDiv[2]=1;//显示雷
          // wx.setStorageSync('slBestScores', 999);//设置最佳时间
          that.setData({
            isTimeStart: 0,//停止计时
            over: 0,
            str: '不好意思，您输了。下次走运！',
            ShowDiv: that.data.ShowDiv,
          })
          


        }
        else {
          console.log('没有雷!');
          //计算格子周围雷数
          that.getNum(x,y);

            that.setData({
              ClassArray: that.data.ClassArray,//更新类数组
              NumArray: that.data.NumArray,//更新数字数组
            })
            that.checkWin();

        }


    }
  },
  leftClick_m: function (x, y) {
    var that = this;
    console.log('leftclick x=' + x + ',y=' + y);
    if (that.data.ClassArray[x][y] == 0) {
      console.log('x=' + x + ',y=' + y + ',islei=' + that.data.LeiMapArray[x][y]);
      //如果有雷
      if (that.data.LeiMapArray[x][y] == 1) {
        console.log('有雷!');
        that.setGameData();//设置游戏数据
        that.data.ShowDiv[0] = 1;//显示gameover盒子
        that.data.ShowDiv[2] = 1;//显示雷
        // wx.setStorageSync('slBestScores', 999);//设置最佳时间
        that.setData({
          isTimeStart: 0,//停止计时
          over: 0,
          str: '不好意思，您输了。下次走运！',
          ShowDiv: that.data.ShowDiv,
        })
      }
      else {
        console.log('没有雷!');
        //计算格子周围雷数
        that.getNum(x, y);

      }


    }
  },
  rightClick:function(x,y){
        //alert('右击')
        var that = this;

        if(that.data.ClassArray[x][y] != 1){
            if(that.data.ClassArray[x][y] == 0 && that.data.playerLeiNum)
            {
                that.data.ClassArray[x][y] = 2;
                that.data.playerLeiNum--;
                that.setData({
                  ClassArray: that.data.ClassArray,
                  playerLeiNum: that.data.playerLeiNum,
                })
                
            }
            else if(that.data.ClassArray[x][y] == 2)
            {
                that.data.ClassArray[x][y] = 0;
                that.data.playerLeiNum++
                that.setData({
                  ClassArray: that.data.ClassArray,
                  playerLeiNum: that.data.playerLeiNum,
                })
                
            }
                
        }
        
    },
  doubleClick: function (x,y) {
    var that = this;
    var XN = that.data.LeiMapY.length;
    var YN = that.data.LeiMapX.length;
    var n = 0;
    for (var xm = x - 1; xm <= x + 1; xm++) {
      for (var ym = y - 1; ym <= y + 1; ym++) {
        if (xm >= 0 && ym >= 0 && xm < XN && ym < YN) {
          if (that.data.ClassArray[xm][ym] == 2)
            n++;
        }
      }
    }
    console.log('flagNum='+n+',Num='+that.data.NumArray[x][y]);
    if(n==that.data.NumArray[x][y])
    {
      for (var xm = x - 1; xm <= x + 1; xm++) {
        for (var ym = y - 1; ym <= y + 1; ym++) {
          if (xm >= 0 && ym >= 0 && xm < XN && ym < YN) {
            if (that.data.ClassArray[xm][ym] == 0) {
              if (!(xm == x && ym == y)) {
                // that.leftClick(xm, ym);
                that.leftClick_m(xm, ym);
              }
            }
          }
        }
      }
      that.setData({
        ClassArray: that.data.ClassArray,//更新类数组
        NumArray: that.data.NumArray,//更新数字数组
      })
      that.checkWin();
  
    }

  },
  getNum: function(x,y){
    var that = this;
    var XN = that.data.LeiMapY.length;
    var YN = that.data.LeiMapX.length;
    var n = 0;
    for (var xm = x - 1; xm <= x + 1; xm++) {
      for (var ym = y - 1; ym <= y + 1; ym++) {
        if (xm >= 0 && ym >= 0 && xm < XN && ym < YN) {
          n += that.data.LeiMapArray[xm][ym];
        }
      }
    }
    // console.log('n='+n);
    that.data.NumArray[x][y] = n;
    that.data.ClassArray[x][y] = 1;//把类改为下
    if(n==0){
      for (var xm = x - 1; xm <= x + 1; xm++) {
        for (var ym = y - 1; ym <= y + 1; ym++) {
          if (xm >= 0 && ym >= 0 && xm < XN && ym < YN) {
            if (that.data.ClassArray[xm][ym] == 0) {
              if (!(xm == x && ym == y)) {
                that.getNum(xm, ym);
              }
            }
          }
        }
      }
    }
    return n;
  },
  checkWin: function () {
    var that = this;
    var YN = that.data.LeiMapY.length;
    var XN = that.data.LeiMapX.length;
    var n = 0;
    for (var r = 0; r < YN; r++) {
      for (var c = 0; c < XN; c++)
        if (that.data.ClassArray[r][c] == 1)
          n++;
    }
    // console.log('n=' + n);
    if(n == YN*XN-that.data.leiNum)
    {
      // console.log('you win!');
      that.data.win = 1;
      that.setGameData();//设置游戏数据
      that.data.ShowDiv[0]=1;//显示gameover盒子
      // that.data.ShowDiv[2]=1;//显示雷
      that.setData({
          isTimeStart: 0,//停止计时
          over: 0,
          win: that.data.win,
          str: '恭喜！您赢了!',
          ShowDiv: that.data.ShowDiv,
        })
    }
      
  },
  checkLeiMap: function () {
    var that = this;
    var YN = that.data.LeiMapY.length;
    var XN = that.data.LeiMapX.length;
    for (var r = 0; r < YN; r++) {
      for (var c = 0; c < XN; c++)
        if (that.data.LeiMapArray[r][c])
          return true;
    }
    return false;
  },
  setmode0:function(){//设置游戏模式0
    this.setData({
      LeiMapX: new Array(9),
      LeiMapY: new Array(9),
      leiNum: 10,
      scrollFlag: false
    })
    this.getWidth();
    this.startGame();//开始函数

  },
  setmode1:function(){//设置游戏模式1
    this.setData({
      LeiMapX: new Array(16),
      LeiMapY: new Array(16),
      leiNum: 40,
      scrollFlag: true,
      tobox0: 'box0'
    })
    this.getWidth();
    this.startGame();//开始函数

  },
  setmode2:function(){//设置游戏模式2
    this.setData({
      LeiMapX: new Array(16),
      LeiMapY: new Array(30),
      leiNum: 99,
      scrollFlag: true,
      tobox0: 'box0'
    })
    this.getWidth();
    this.startGame();//开始函数

  },
  suofang:function(){
    //0屏幕宽度，1小盒子宽度，2游戏盒子宽度,3游戏盒子高度
    //WidthArray: ['360px', '40px', '360px', '360px'],
    if (this.data.leiNum>10){
      if (this.data.scrollFlag){
        let scale1 = (0.77 * this.data.vh100) / this.data.WidthArray[3];
        let scale2 = this.data.WidthArray[0] / this.data.WidthArray[2];
        let minScale = scale1 < scale2 ? scale1 : scale2;
        this.setData({
          scaleNum: minScale,
          scrollFlag: false,
          tobox0: 'box0'
        });
      }
      else{
        this.setData({
          scaleNum: 1,
          scrollFlag: true,
          tobox0: ''
        });
      }
      

    }
    


  },
  test1:function(){//测试1
    wx.clearStorageSync();
    this.startGame();
  },
  test2:function(){//测试2
    console.log(this.data.ShowDiv[2]);
    var temp = this.data.ShowDiv;
    if (temp[2] == 0)
      temp[2] = 1;
    else
      temp[2] = 0;

    this.setData({//更新数据
      ShowDiv: temp,
    })
    
  },
  test3:function(){//测试3
  console.log(this.data.ShowDiv);
    
  },
  setClassArray:function(){
    var that = this;
    var YN = that.data.LeiMapY.length;
    var XN = that.data.LeiMapX.length;
    
    console.log(that.data.ClassArray.join("\n"));
    that.setData({//更新数据
      ClassArray: that.data.ClassArray,
    })
  },
  setNumArray:function(){
    var that = this;
    var YN = that.data.LeiMapY.length;
    var XN = that.data.LeiMapX.length;

    console.log(that.data.NumArray.join("\n"));
    that.setData({//更新数据
      NumArray: that.data.NumArray,
    })
  },
  setLeiArray: function (x,y) {//设置雷数组
    var that = this;
    // var x=0,y=0;
    var lei = that.data.leiNum;
    var YN = that.data.LeiMapY.length;
    var XN = that.data.LeiMapX.length;
    // console.log(x,y)
    
    //布置雷
    while (lei) {
      var r = Math.floor(Math.random() * YN);
      var c = Math.floor(Math.random() * XN);
      if (that.data.LeiMapArray[r][c] == 0 && !(r >= x - 1 && r <= x + 1 && c >= y - 1 && c <= y + 1)) {
        that.data.LeiMapArray[r][c] = 1;
        // document.getElementById(r + '_' + c).classList.add('isLei');
        lei--;
      }
    }
    // console.clear();
    console.log(that.data.LeiMapArray.join("\n"));
    that.setData({//更新数据
      LeiMapArray: that.data.LeiMapArray,
      ClassArray: that.data.ClassArray,
      NumArray: that.data.NumArray,
    })

  },
  setTime:function(){
    var that = this;
    var time = 0;
    setInterval(function () {
      if (that.data.isTimeStart)
        {
          time = that.data.showtime;
          time++;
          that.setData({
            showtime:time,
          })
          // console.log(time)
        }
    }, 1000);
    
  },
  selectmode:function(){
    var m = this.data.ShowDiv[1];
    if(m==0)
      m=1;
    else
      m=0;
    this.data.ShowDiv[1]=m;
    this.setData({
      ShowDiv: this.data.ShowDiv,
    })
    
  },
  touchStartTime: 0,// 触摸开始时间
  touchEndTime: 0,// 触摸结束时间
  lastTapTime: 0,// 最后一次单击事件点击发生时间
  lastTapTimeoutFunc: null,// 单击事件点击后要触发的函数
  touchStart: function (e) {// 按钮触摸开始触发的事件
    this.touchStartTime = e.timeStamp
  },
  touchEnd: function (e) {// 按钮触摸结束触发的事件
    this.touchEndTime = e.timeStamp
  },
  // 判断单击双击
  onclick: function (e) {
    var that = this;
    var x = e.currentTarget.dataset.posx;
    var y = e.currentTarget.dataset.posy;
    if(that.data.scrollFlag){
      // 控制点击事件在350ms内触发，加这层判断是为了防止长按时会触发点击事件
      if (that.touchEndTime - that.touchStartTime < 350) {
        // 当前点击的时间
        var currentTime = e.timeStamp
        var lastTapTime = that.lastTapTime
        // 更新最后一次点击时间
        that.lastTapTime = currentTime

        // 如果两次点击时间在200毫秒内，则认为是双击事件
        if (currentTime - lastTapTime < 200) {
          // console.log("双击"+x+'_'+y)
          that.doubleClick(x, y);
          // 成功触发双击事件时，取消单击事件的执行
          clearTimeout(that.lastTapTimeoutFunc);
        } else {
          // 单击事件延时200毫秒执行，这和最初的浏览器的点击300ms延时有点像。
          that.lastTapTimeoutFunc = setTimeout(function () {
            // console.log('单击'+x + '_' + y);
            if (that.data.clickmode == 0)
              that.leftClick(x, y);
            else
              that.rightClick(x, y);
          }, 200);
        }
      }
    }
    else{
      that.setData({
        scaleNum: 1,
        scrollFlag: true,
        tobox0: ''
      });
    }
    

  },
  getWidth:function(){
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var t = res.windowWidth / 9;
        that.vh100 = res.windowHeight;
        console.log(res.windowHeight);
        var ts = parseInt((t)*100)/100;
        that.data.WidthArray[0] = res.windowWidth;
        that.data.WidthArray[1] = ts;
        if (that.data.leiNum==10)
        {
          that.data.WidthArray[2] = res.windowWidth;
          that.data.WidthArray[3] = res.windowWidth;
        }
        else
        {
          that.data.WidthArray[2] = parseInt(t * that.data.LeiMapX.length * 100) / 100;
          that.data.WidthArray[3] = parseInt(t * that.data.LeiMapY.length * 100) / 100;
        }
        that.setData({
          WidthArray: that.data.WidthArray,
          vh100: that.vh100
        })

      }
    })
    console.log('width=' + that.data.WidthArray);

  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    //开启界面时开始计时
    if (that.data.over == 1){
      that.setData({
        isTimeStart: 1,
      })

    }
    

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    var that = this;
    //隐藏界面时暂停计时
    that.setData({
      isTimeStart:0,
    })

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})